import os, boto3, json
from django.db import models
from django import forms
from django.template.loader import render_to_string
from django.conf import settings


class CustomFileInput(forms.TextInput):
    # 重写render方法，使用自定义的HTML模板

    def __init__(self, field_name, model_name, max_upload_size, attrs=None):
        self.field_name = field_name
        self.model_name = model_name
        self.max_upload_size = max_upload_size
        super().__init__(attrs)

    def render(self, name, value, attrs=None, renderer=None):
        # 调用父类的render方法，获取默认的HTML代码
        if value:
            filename = value.split("/")[-1]
        else:
            filename = ''
        html = super().render(name, value, attrs, renderer) # 保持原有widget.
        html += render_to_string('ossfilefield/oss_file.html', {
            'download_url': settings.OSS_FILE_DOWNLOAD_URL,
            'upload_url': settings.OSS_FILE_UPLOAD_URL,
            'filename': filename,
            'value':value,
            'max_upload_size': self.max_upload_size,
            'field_name':self.field_name,
            'model_name':self.model_name,
        })
        # 返回HTML代码
        return html


class OssFileField(models.TextField):
    '''
    Example: module_name/202302/filename.uuid.pdf
    max_upload_size: in kb, default is 1Gb.
    '''
    def __init__(self, *args, upload_to="", max_upload_size = 1*1024*1024, **kwargs):
        if upload_to.startswith("/"):
            upload_to = upload_to[1:]
        self.upload_to = upload_to
        self.max_upload_size = max_upload_size
        super().__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        # 往原生widget后面加外挂.
        kwargs["widget"] = CustomFileInput(
            field_name=self.name,
            model_name = self.model._meta.label,
            max_upload_size = self.max_upload_size
        )
        return super().formfield(**kwargs)




